package jsyf.oa.service.report.wechatRelay;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.WechatConstant;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.report.wechatRelay.WechatDao;
import jsyf.oa.dao.report.wechatRelay.WechatDetailDao;
import jsyf.oa.dao.system.CompanyDao;
import jsyf.oa.dao.system.MessageDao;
import jsyf.oa.dao.system.MessageReceiverDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.facade.report.wechatRelay.WechatShareFacade;
import jsyf.oa.service.report.reportCommon.ReportCommonMethodsAndConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by y on 2018/4/4.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WechatService implements WechatShareFacade {
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private WechatDetailDao wechatDetailDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ReportCommonMethodsAndConstant common;

    @Override
    public JSONObject getWechatTotal(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        int length = DateTime.length();
        JSONObject userJson = userDao.getViewJSONListByCondition(" AND id = ? AND main = 1 ", new Object[]{userId}).get(0);
        String companyId = userJson.get("companyId").toString();
        String roleName = userJson.get("roleName").toString();
        JSONObject result = new JSONObject();
        //Calendar calendar = Calendar.getInstance();
        //String today = DateUtils.parse(calendar.getTime(), "yyyy-MM-dd");
        if (length == 10) {
            //获取当天的分享记录
            result = wechatDao.getWechatShareToday(DateTime, companyId, userId, roleName);
            Integer todayForward = Integer.valueOf(result.getString("forward"));
            Integer todayFinishForward = Integer.valueOf(result.getString("finishForward"));
            result.put("noForward", todayForward - todayFinishForward < 0 ? 0 : todayForward - todayFinishForward);
        } else {
            //获取某月的分享记录
            result = wechatDao.getWechatShareMonth(DateTime, companyId, userId, roleName);
            Integer monthForward = Integer.valueOf(result.getString("forward"));
            Integer monthFinishForward = Integer.valueOf(result.getString("finishForward"));
            result.put("noForward", monthForward - monthFinishForward < 0 ? 0 : monthForward - monthFinishForward);
        }
        return result;
    }

    @Override
    public JSONObject getWechatTotalforDepartByuserId(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        int length = DateTime.length();
        JSONObject userJson = userDao.getViewJSONListByCondition(" AND id = ? AND main = 1 ", new Object[]{userId}).get(0);
        String companyId = userJson.get("companyId").toString();
        JSONObject result = new JSONObject();
        //Calendar calendar = Calendar.getInstance();
        //String today = DateUtils.parse(calendar.getTime(), "yyyy-MM-dd");
        if (length == 10) {
            //获取当天的分享记录
            result = wechatDao.getForDepartTotalTodayByuserId(DateTime, companyId, userId);
            Integer todayForward = Integer.valueOf(result.getString("forward"));
            Integer todayFinishForward = Integer.valueOf(result.getString("finishForward"));
            result.put("noForward", todayForward - todayFinishForward < 0 ? 0 : todayForward - todayFinishForward);
        } else {
            //获取某月的分享记录
            result = wechatDao.getForDepartTotalMonthByuserId(DateTime, companyId, userId);
            Integer monthForward = Integer.valueOf(result.getString("forward"));
            Integer monthFinishForward = Integer.valueOf(result.getString("finishForward"));
            result.put("noForward", monthForward - monthFinishForward < 0 ? 0 : monthForward - monthFinishForward);
        }
        return result;
    }

    @Override
    public List<JSONObject> getForPersonalByUserIdAndDateTime(JSONObject jsonObject) {
        String dateTime = jsonObject.getString("dateTime");
        String userId = jsonObject.getString("userId");
        JSONObject User = userDao.getViewJSONById(userId);
        String companyId = User.getString("companyId");
        int length = dateTime.length();
        //返回的集合
        List<JSONObject> dayList = new ArrayList<>();
        //当月截止到当天的天数
        List<String> arrayDayList = new ArrayList<>();
        //当前日期
        Calendar c = Calendar.getInstance();
        String month = DateUtils.parse(c.getTime(), "yyyy-MM");
        if (10 == length) {
            List<JSONObject> Todaylist = wechatDao.getWechatShareList(userId, dateTime, companyId);
            for (Integer i = 0; i < Todaylist.size(); i++) {
                String id = Todaylist.get(i).getString("id");
                StringBuffer condition = new StringBuffer();
                if (StringUtils.isNotEmpty(dateTime)) {
                    condition.append(" AND DATE_FORMAT(CREATE_TIME,'%Y-%m-%d')=? ");
                }
                if (StringUtils.isNotEmpty(userId)) {
                    condition.append(" AND USER_ID=? ");
                }
                condition.append(" AND WECHAT_SHARE_ID=? ");
                condition.append(" AND DEL_FLAG=0");
                Todaylist.get(i).put("morningFlag", false);
                Todaylist.get(i).put("noonFlag", false);
                Todaylist.get(i).put("nightFlag", false);
                Todaylist.get(i).put("sort", i + 1);
                //查询某人某天的分享记录
                List<JSONObject> detailList = wechatDetailDao.getJSONListByCondition(condition.toString(), new Object[]{dateTime, userId, id});
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Integer j = 0; j < detailList.size(); j++) {
                    String createtime = detailList.get(j).getString("createTime");
                    Date createTime = null;
                    try {
                        createTime = sdf.parse(createtime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    //判断上午是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.morningStart, WechatConstant.morningEnd)) {
                        Todaylist.get(i).put("morningFlag", true);
                    }
                    //判断中午是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.noonStart, WechatConstant.noonEnd)) {
                        Todaylist.get(i).put("noonFlag", true);
                    }
                    //判断晚上是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.nightStart, WechatConstant.nightEnd)) {
                        Todaylist.get(i).put("nightFlag", true);
                    }

                }
            }
            return Todaylist;
        }
        if (dateTime.equals(month)) {
            //当月，获取当天是本月的第几天
            Integer days = c.get(Calendar.DAY_OF_MONTH);
            for (Integer i = days; i >= 1; i--) {
                arrayDayList.add(dateTime + "-" + (i < 10 ? ("0" + i) : i));
            }
        } else {
            //非当月，获取某月最后一天
            Integer lastDay = DateUtils.getLastDayOfMonth(Integer.valueOf(dateTime.split("-")[0]), Integer.valueOf(dateTime.split("-")[1]));
            for (Integer i = lastDay; i >= 1; i--) {
                arrayDayList.add(dateTime + "-" + (i < 10 ? ("0" + i) : i));
            }
        }
        //分享信息赋值
        for (Integer i = 0; i < arrayDayList.size(); i++) {
            String shareDate = arrayDayList.get(i);
            //获取每天分享链接列表
            List<JSONObject> list = wechatDao.getWechatShareList(userId, shareDate, companyId);
            for (Integer j = 0; j < list.size(); j++) {
                String id = list.get(j).getString("id");
                StringBuffer condition = new StringBuffer();
                if (StringUtils.isNotEmpty(shareDate)) {
                    condition.append(" AND DATE_FORMAT(CREATE_TIME,'%Y-%m-%d')=? ");
                }
                if (StringUtils.isNotEmpty(userId)) {
                    condition.append(" AND USER_ID=? ");
                }
                condition.append(" AND WECHAT_SHARE_ID=? ");
                condition.append(" AND DEL_FLAG=0");
                list.get(j).put("morningFlag", false);
                list.get(j).put("noonFlag", false);
                list.get(j).put("nightFlag", false);
                list.get(j).put("sort", j + 1);
                //查询某人某天对某个链接的分享记录
                List<JSONObject> detailList = wechatDetailDao.getJSONListByCondition(condition.toString(), new Object[]{shareDate, userId, id});
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Integer k = 0; k < detailList.size(); k++) {
                    //获取当条记录的创建时间
                    String createtime = detailList.get(k).getString("createTime");
                    Date createTime = null;
                    try {
                        createTime = sdf.parse(createtime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    //上午是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.morningStart, WechatConstant.morningEnd)) {
                        list.get(j).put("morningFlag", true);
                    }
                    //中午是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.noonStart, WechatConstant.noonEnd)) {
                        list.get(j).put("noonFlag", true);
                    }
                    //晚上是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.nightStart, WechatConstant.nightEnd)) {
                        list.get(j).put("nightFlag", true);
                    }
                }
                dayList.add(list.get(j));
            }
        }
        return dayList;
    }

    @Override
    public List<JSONObject> getTodayWechatShare(JSONObject jsonObject) {
        String dateTime = jsonObject.getString("dateTime");
        String userId = jsonObject.getString("userId");
        JSONObject User = userDao.getViewJSONById(userId);
        String companyId = User.getString("companyId");
        dateTime = DateUtils.getYesterDayByTime(dateTime, 19);
        List<JSONObject> Todaylist = wechatDao.getTodayWechatShareList(dateTime, companyId);
        for (Integer i = 0; i < Todaylist.size(); i++) {
            String id = Todaylist.get(i).getString("id");
            StringBuffer condition = new StringBuffer();
            if (StringUtils.isNotEmpty(dateTime)) {
                condition.append(" AND DATE_FORMAT(CREATE_TIME,'%Y-%m-%d')=? ");
            }
            if (StringUtils.isNotEmpty(userId)) {
                condition.append(" AND USER_ID=? ");
            }
            condition.append(" AND WECHAT_SHARE_ID=? ");
            condition.append(" AND DEL_FLAG=0");
            Todaylist.get(i).put("morningFlag", false);
            Todaylist.get(i).put("noonFlag", false);
            Todaylist.get(i).put("nightFlag", false);
            Todaylist.get(i).put("sort", i + 1);
            //查询某人某天的分享记录
            List<JSONObject> detailList = wechatDetailDao.getJSONListByCondition(condition.toString(), new Object[]{dateTime, userId, id});
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Integer j = 0; j < detailList.size(); j++) {
                String createtime = detailList.get(j).getString("createTime");
                Date createTime = null;
                try {
                    createTime = sdf.parse(createtime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //判断上午是否分享
                if (DateUtils.isInDate(createTime, WechatConstant.morningStart, WechatConstant.morningEnd)) {
                    Todaylist.get(i).put("morningFlag", true);
                }
                //判断中午是否分享
                if (DateUtils.isInDate(createTime, WechatConstant.noonStart, WechatConstant.noonEnd)) {
                    Todaylist.get(i).put("noonFlag", true);
                }
                //判断晚上是否分享
                if (DateUtils.isInDate(createTime, WechatConstant.nightStart, WechatConstant.nightEnd)) {
                    Todaylist.get(i).put("nightFlag", true);
                }
            }
        }
        return Todaylist;
    }

    @Override
    public List<JSONObject> getTodayWechatContact(JSONObject jsonObject) {
        String dateTime = jsonObject.getString("dateTime");
        String userId = jsonObject.getString("userId");
        JSONObject User = userDao.getViewJSONById(userId);
        String companyId = User.getString("companyId");
        List<JSONObject> contacts = new ArrayList<JSONObject>();
        for (int i = 0; i < 5; i++) {
            JSONObject contact = wechatDao.getTodayWechatContact(userId, wechatDao.getdate(i), companyId);
            if (contact == null) {
                JSONObject o = new JSONObject();
                o.put("createTime", wechatDao.getdate(i));
                o.put("contact", "");
                JSONObject checkIsLeave = wechatDao.checkIsLeave(userId, wechatDao.getdate(i));
                if (checkIsLeave != null) {
                    o.put("contact", "请假");
                }
                o.put("num", "");
                o.put("img", "");
                contacts.add(o);
            } else {
                contacts.add(contact);
            }
        }
        return contacts;
    }

    @Override
    public Boolean regionRemind() {
        //获取所有的区域经理
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" AND roleName=? AND jobState!=1 and main=1 ", new Object[]{"区域经理"});
        String user="'',";
        if (userList != null && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                user=user+"'"+userList.get(i).getString("id")+"',";
            }
        }
        if (!StringUtils.isBlank(user)){
            user=user.substring(0,user.length()-1);
        }
        List<JSONObject> regionList=wechatDao.getWechatBhg(user,DateUtils.nowDayByString(userDao.getCurrentTime()));
        for (int j=0;j<regionList.size();j++){
            this.sendMessage(regionList.get(j),"/reportForm/errorMessage/quYuWeChatApp.html?userId="+regionList.get(j).getString("userId")+"&dateTime="+DateUtils.nowDateByString(userDao.getCurrentTime()));
        }
        return true;
    }

    @Override
    public Boolean bigRegionRemind() {
        //获取所有的组长大区
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" AND roleName in ('大区经理','区域组长') AND jobState!=1 and main=1", new Object[]{});
        if (userList != null && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                JSONObject user = new JSONObject();
                user.put("userId", userList.get(i).getString("id"));
                user.put("dateTime", DateUtils.nowDateByString(userDao.getCurrentTime()));
                List<JSONObject> userWhat = this.getForDepartByUserIdAndDateTime(user);
                for (int j = 0; j < userWhat.size(); j++) {
                    //判断等于0发消息
                    if (!userWhat.get(j).getString("forward").equals("0") && !userWhat.get(j).getString("noForward").equals("0")) {
                        this.sendMessage(user, "/reportForm/errorMessage/daQuWeChatApp.html?userId="+user.getString("userId")+"&dateTime="+user.getString("dateTime"));
                        break;
                    }
                }
            }
        }
        return true;
    }

    public void sendMessage(JSONObject user, String url) {
        //保存消息到消息表t_sys_message
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setCreateUserId(user.getString("userId"));
        messageEntity.setCreateTime(userDao.getCurrentTime());
        messageEntity.setContent("微信转发违规");
        messageEntity.setMessageType(3);
        messageEntity.setDelFlag(0);
        messageEntity.setOpenUrl(url);
        messageEntity.setOpenTitle(String.format(WECHAT_FORWARD_MESSAGE_ERROR));
        messageDao.add(messageEntity);
        //保存第一审核人信息到消息收件人表t_sys_message_receiver
        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
        messageReceiverEntity.setMessageId(messageEntity.getId());
        messageReceiverEntity.setUserId(user.getString("userId"));
        messageReceiverEntity.setUserType(0);
        messageReceiverEntity.setReadFlag(0);
        messageReceiverDao.add(messageReceiverEntity);
        //发送企业微信
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", messageEntity.getCreateUserId());
        msgObject.put("content", String.format(WECHAT_FORWARD_MESSAGE_ERROR_WE,
                "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl()));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
    }

    @Override
    public List<JSONObject> getForDepartByUserIdAndDateTime(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        int length = DateTime.length();
        JSONObject userJson = userDao.getViewJSONListByCondition(" AND id = ? AND main = 1 ", new Object[]{userId}).get(0);
        String companyId = userJson.get("companyId").toString();
        String frontFlag = userJson.get("frontFlag").toString();
        List<JSONObject> result = new ArrayList<JSONObject>();
        //获取当天的分享记录
        List<JSONObject> list = wechatDao.getForDepartByUserIdAndDateTimeToday(DateTime, companyId, userId, frontFlag);
        return list;
    }

    @Override
    public List<JSONObject> getForCompanyByUserIdAndDateTime(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        List<JSONObject> result = wechatDao.getForCompanyByUserIdAndDateTime(DateTime, userId);
        return result;
    }

    @Override
    public JSONObject getWechatTotalforCompany(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        return wechatDao.getWechatTotalforCompany(DateTime, userId);
    }

    @Override
    public List<JSONObject> getForDepartBydepartId(JSONObject jsonObject) {
        String DateTime = jsonObject.getString("dateTime");
        String departId = jsonObject.getString("departId");
        List<JSONObject> result = wechatDao.getForDepartBydepartId(DateTime, departId);
        return result;
    }

    @Override
    public List<JSONObject> getForGroupByUserIdAndDateTime(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id = ? ", new Object[]{userId});
        List<String> listCompanyIds = new ArrayList<>();
        String companyIds = "";
        for (int i = 0; i < userList.size(); i++) {
            String companyId = userList.get(i).getString("companyId");
            String manageFlag = userList.get(i).getString("manageFlag");
            if (manageFlag.equals("1")) {
                companyDao.getChildrenIds(companyId, listCompanyIds);
                for (int j = 0; j < listCompanyIds.size(); j++) {
                    companyIds += "'" + listCompanyIds.get(j) + "',";
                }
            } else {
                companyIds += "'" + companyId + "',";
            }
            if (companyIds.length() > 0) {
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            }
        }
        List<JSONObject> result = wechatDao.getForGroupByUserIdAndDateTime(DateTime, companyIds);
        return result;
    }

    @Override
    public JSONObject getWechatTotalforGroup(JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String DateTime = jsonObject.getString("dateTime");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id = ? ", new Object[]{userId});
        List<String> listCompanyIds = new ArrayList<>();
        String companyIds = "";
        for (int i = 0; i < userList.size(); i++) {
            String companyId = userList.get(i).getString("companyId");
            String manageFlag = userList.get(i).getString("manageFlag");
            if (manageFlag.equals("1")) {
                companyDao.getChildrenIds(companyId, listCompanyIds);
                for (int j = 0; j < listCompanyIds.size(); j++) {
                    companyIds += "'" + listCompanyIds.get(j) + "',";
                }
            } else {
                companyIds += "'" + companyId + "',";
            }
            if (companyIds.length() > 0) {
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            }
        }
        return wechatDao.getForGroupTotal(DateTime, companyIds);
    }

    @Override
    public List<JSONObject> getForCompanyByCompanyId(JSONObject jsonObject) {
        String companyId = jsonObject.getString("companyId");
        String DateTime = jsonObject.getString("dateTime");
        List<JSONObject> result = wechatDao.getForCompanyByCompanyId(DateTime, companyId);
        return result;
    }

    @Override
    public JSONObject getWechatTotalforDepart(JSONObject jsonObject) {
        String departId = jsonObject.getString("departId");
        String DateTime = jsonObject.getString("dateTime");
        return wechatDao.getWechatTotalforDepart(DateTime, departId);
    }

    @Override
    public List<JSONObject> getForDepartBycompanyId(JSONObject jsonObject) {
        String companyId = jsonObject.getString("companyId");
        String DateTime = jsonObject.getString("dateTime");
        List<JSONObject> result = wechatDao.getForDepartBycompanyId(DateTime, companyId);
        return result;
    }

    @Override
    public JSONObject getWechatTotalforDepartByCompanyId(JSONObject jsonObject) {
        String companyId = jsonObject.getString("companyId");
        String dateTime = jsonObject.getString("dateTime");
        return wechatDao.getForDepartTotal(dateTime, companyId);
    }
}